<?php

namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;

class UploadController extends BaseController
{

    /**
     * api上传图片
     * @param Request $request
     * @return array
     */
    public function uploadImg(Request $request){
        if($request->hasFile('avatar')){
            $file = $request->file('avatar');//从请求数据内容中取出图片的内容
            //gif|jpe?g|png|doc|xls|xlsx|docx
            $allowed_extensions = ["gif","jpeg","jpg","png"]; //允许的图片后缀
//            $allowed_extensions = ["gif","jpeg","jpg","png","doc","xls","xlsx","docx"]; //允许的图片后缀
            if($file->getClientOriginalExtension() && !in_array($file->getClientOriginalExtension(), $allowed_extensions)) {

                $data = [];
                $data['code'] = 0;
                $data['msg']   = '图片后缀只支持png,jpg,gif,文件后缀只支持doc,xls,xlsx,docx。请检查！';

                return $data;
            }

            $extension  =  $file->extension();
            if(!in_array($extension, $allowed_extensions)){
                $extension = $file->getClientOriginalExtension();
            }

            $file_url   =  $file->storeAs('file/'.date("Ymd"),str_random(32).'.'.$extension,'file');
            $data = [];
            $data['code'] = 1;
            $data['file_src'] = $file_url;
            $data['msg'] = '上传成功';
            $data['url'] ='/' .$file_url ; //输出图片网站中浏览路径

            return $data;
        }
    }

}
